package shc.graduation.http.task;

import org.litepal.crud.DataSupport;

import java.util.List;

import shc.graduation.bean.PaoWangArticle;
import shc.graduation.bean.PaoWangGroup;
import shc.graduation.utils.log.LogUtils;

/**
 * Created by shuhuiChen on  2016/5/21  18:07.
 * Email ：shuhuiCSH@126.com
 */
public class PaoWangArticleTask extends BaseTask<PaoWangArticle> {

    @Override
    void executeTask() {

        if (mBaseGetter == null)
            return;

        boolean isStop = false;  //是否暂停继续抓取网页内容
        int index = mTaskOption.pageIndex; //开始的索引
        // 在这里检查数据库是否已经存在了
        PaoWangGroup paoWangGroup = DataSupport.find(PaoWangGroup.class, mTaskOption.groupIndex);
        if (paoWangGroup == null) {
            ListenerFail("没有该分组");
            return;
        }

        List<PaoWangArticle> articleList = null;

        while (!isStop) {

            String url = mTaskOption.websiteUrl + index;// 拼接请求网址链接

            ListenerRunning("正在请求第" + index + "页");
            mModelList = mBaseGetter.getModel(url);

            if (mModelList != null) {
                LogUtils.e("返回对象数量:" + mModelList.size());
            }

            if (mModelList != null && mModelList.size() > 0) {

                ListenerRunning("请求的网页内容有东西");

                for (PaoWangArticle article : mModelList) {

                    articleList = DataSupport.where("contentUrl = ?", article.getContentUrl()).find(PaoWangArticle.class);

                    if (articleList != null && articleList.size() <= 0) {

                        ListenerRunning(article.getTitle() + "：数据库中木有");

                        article.setPaowanggroup_id(paoWangGroup.getId());
                        article.setGroupName(paoWangGroup.getGroupName());
                        article.save();

                        ListenerRunning(article.getTitle() + "：保存好了");
                        LogUtils.e("保存好了");
                    } else {

                        ListenerRunning(article.getTitle() + "：数据库中已存在");
                        isStop = true;
                        ListenerSuccess("成功");
                        LogUtils.e("数据库中已存在，停止循环");
                        break;//跳出这个循环
                    }
                }
            } else {
                isStop = true;
                ListenerSuccess("成功");
                LogUtils.e("数据为空，停止循环");
            }
            index++;
            if (mModelList != null) {
                mModelList.clear();
                mModelList = null;
            }
        }
    }

}
